package smtp;

import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;

import server.Server;

public class QuotedEncoder {
	public static final int CODE_EQUAL = 61;
	public static final int CODE_DOT = 46;
	
	private String lastline = "";
	private String lines = "";
	
	
	
	public String quoted(int b) {
		return "=" + Integer.toHexString(b).toUpperCase();
	}
	
	public void safeAppend(String c) {
		int current = lastline.length();
		int appendix = c.length();
		if (current + appendix > 77) {
			this.lastline += "=\n";
			this.lines += lastline;
			this.lastline = "";
			this.lastline += c;				
		}
		else {
			this.lastline += c;
		}		
	}
	
	public String encode(String s) {
		
		try {
			byte[] bytes = s.getBytes("ISO-8859-15");
		} catch (UnsupportedEncodingException e) {
			Logger.getLogger(Server.LOG).severe("Unsupported encoding for body");
		} //"ISO-8859-15");
		catch (Exception e ) {
		}
		
		this.lines = "";
		this.lastline = "";

		for (int i = 0; i < s.length(); i++) {
			char character = s.charAt(i);	
			char[] tmp = {character};
			String cc = new String(tmp);
			int b = (int) character;
			
			if (b == CODE_EQUAL) {				
				this.safeAppend(this.quoted(character));
			}
			else if (b == CODE_DOT) {
				this.safeAppend(this.quoted(character));
			}
			else if ((b >= 9) && (b <= 32)){ // White space
				this.safeAppend(cc);
			}
			else if ((b >= 33) && (b <= 126)){ // White space
				this.safeAppend(cc);
			}	
			else if (b > 126) {
				this.safeAppend(this.quoted(character));
			}										
		}
		
		if (lastline.length() > 0) {
			lines += lastline;
		}
		return lines;
	}
	
	/*
	public static void main(String[] args){
		QuotedEncoder encoder = new QuotedEncoder();		
		System.out.println(encoder.encode("I flera veckor har människor i Syrien protesterat mot landets ledare. De vill ha demokrati i landet. Protesterna har stoppats med våld. Troligen har mer än hundra människor dödats."));
	}
	*/
}
